﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XcoAppSpaces.Core;
using Microsoft.Ccr.Core;
using System.Threading;
using NUnit.Framework;

namespace test.XcoAppSpaces.Core
{
	[TestFixture]
	public class testCcrThreadOccupation
	{
		class SleepWorker : Port<int> //worker for testing occupied ccr threads
		{
			[XcoConcurrent]
			public void ProcessInt(int msg)
			{
				Console.WriteLine("Ccr Thread sleeping ...");
				Thread.Sleep(msg);
				Console.WriteLine("Ccr Thread waking up.");
			}
		}

		[Test]
		public void TestConnectWorkerDuringFullCcrOccupation()
		{
			//ConnectWorker must work even if all ccr threads are currently occupied!
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000;ccr.threadcount=2"),
				space2 = new XcoAppSpace("tcp.port=8001;ccr.threadcount=2"))
			{
				var port = new Port<int>();
				space1.RunWorker(port);

				Console.WriteLine("Space 1 Worker Threads: " + space1.DefaultDispatcher.WorkerThreadCount);
				Console.WriteLine("Space 2 Worker Threads: " + space2.DefaultDispatcher.WorkerThreadCount);
				var sw1 = space1.RunWorker(new SleepWorker());
				var sw2 = space2.RunWorker(new SleepWorker());
				sw1.Post(5000);
				sw1.Post(5000);
				sw2.Post(5000);
				sw2.Post(5000);

				var remotePort = space2.ConnectWorker<Port<int>>(Environment.MachineName + ":8000");

				Console.WriteLine("Sucessfully connected to worker!");
				//Thread.Sleep(2000);
			}
		}
	}
}
